<template>
  <div class="app-container">
    <el-card>
      <div slot="header" class="clearfix">
        <span>{{ isEdit ? '修改商品' : '新增商品' }}</span>
      </div>

      <el-form ref="form" :model="form" :rules="rules" label-width="120px">
        <el-row :gutter="20">
          <el-col :xs="24" :sm="12" :md="8" :lg="6" :xl="6">
            <el-form-item label="商品编码" prop="productCode">
              <coding-input
                ref="productCodeInput"
                v-model="form.productCode"
                table-name="ec_product"
                field-name="product_code"
                :is-edit="isEdit"
                :enable-auto-generate="true"
                :show-preview="true"
                :show-refresh="true"
                placeholder="请输入商品编码或点击生成"
                @code-generated="handleCodeGenerated"
              />
            </el-form-item>
          </el-col>
          <el-col :xs="24" :sm="12" :md="8" :lg="6" :xl="6">
            <el-form-item label="商品名称" prop="productName">
              <el-input v-model="form.productName" placeholder="请输入商品名称" />
            </el-form-item>
          </el-col>
          <el-col :xs="24" :sm="12" :md="8" :lg="6" :xl="6">
            <el-form-item label="商品分类" prop="categoryId">
              <id-selector
                v-model="form.categoryId"
                placeholder="请选择商品分类"
                dialog-title="选择商品分类"
                :api-function="listCategory"
                :get-api-function="getCategory"
                id-field="categoryId"
                name-field="categoryName"
                id-label="分类ID"
                name-label="分类名称"
                search-label="分类名称"
                search-placeholder="请输入分类名称"
                :extra-columns="[{prop: 'categoryCode', label: '分类编码'}]"
              />
            </el-form-item>
          </el-col>
          <el-col :xs="24" :sm="12" :md="8" :lg="6" :xl="6">
            <el-form-item label="商品品牌" prop="brandId">
              <id-selector
                v-model="form.brandId"
                placeholder="请选择商品品牌"
                dialog-title="选择商品品牌"
                :api-function="listBrand"
                :get-api-function="getBrand"
                id-field="brandId"
                name-field="brandName"
                id-label="品牌ID"
                name-label="品牌名称"
                search-label="品牌名称"
                search-placeholder="请输入品牌名称"
                :extra-columns="[{prop: 'brandCode', label: '品牌编码'}]"
              />
            </el-form-item>
          </el-col>
        </el-row>

        <!-- 商品展示价格字段 -->
        <el-row :gutter="20">
          <el-col :xs="24" :sm="12" :md="8" :lg="6" :xl="6">
            <el-form-item label="商品展示价格" prop="price">
              <el-input-number v-model="form.price" :precision="2" :min="0" placeholder="请输入商品展示价格" style="width: 100%" />
            </el-form-item>
          </el-col>
        </el-row>

        <!-- 其他价格和库存相关字段已隐藏，在SKU中配置 -->
        <!-- <el-row :gutter="20">
          <el-col :xs="24" :sm="12" :md="8" :lg="6" :xl="6">
            <el-form-item label="原价" prop="originalPrice">
              <el-input v-model="form.originalPrice" placeholder="请输入原价" />
            </el-form-item>
          </el-col>
          <el-col :xs="24" :sm="12" :md="8" :lg="6" :xl="6">
            <el-form-item label="成本价" prop="costPrice">
              <el-input v-model="form.costPrice" placeholder="请输入成本价" />
            </el-form-item>
          </el-col>
          <el-col :xs="24" :sm="12" :md="8" :lg="6" :xl="6">
            <el-form-item label="库存数量" prop="stock">
              <el-input v-model="form.stock" placeholder="请输入库存数量" />
            </el-form-item>
          </el-col>
        </el-row> -->

        <el-row :gutter="20">
          <!-- <el-col :xs="24" :sm="12" :md="8" :lg="6" :xl="6">
            <el-form-item label="库存预警值" prop="lowStock">
              <el-input v-model="form.lowStock" placeholder="请输入库存预警值" type="number" />
            </el-form-item>
          </el-col> -->
          <!-- <el-col :xs="24" :sm="12" :md="8" :lg="6" :xl="6">
            <el-form-item label="单位" prop="unit">
              <el-input v-model="form.unit" placeholder="请输入单位" />
            </el-form-item>
          </el-col> -->
          <!-- <el-col :xs="24" :sm="12" :md="8" :lg="6" :xl="6">
            <el-form-item label="重量" prop="weight">
              <el-input v-model="form.weight" placeholder="请输入重量" type="number" />
            </el-form-item>
          </el-col>
          <el-col :xs="24" :sm="12" :md="8" :lg="6" :xl="6">
            <el-form-item label="体积" prop="volume">
              <el-input v-model="form.volume" placeholder="请输入体积" type="number" />
            </el-form-item>
          </el-col> -->
        </el-row>

        <el-row :gutter="20">
          <el-col :xs="24" :sm="12" :md="8" :lg="6" :xl="6">
            <el-form-item label="销量" prop="saleCount">
              <el-input v-model="form.saleCount" placeholder="系统自动统计" :disabled="true" />
            </el-form-item>
          </el-col>
          <el-col :xs="24" :sm="12" :md="8" :lg="6" :xl="6">
            <el-form-item label="浏览量" prop="viewCount">
              <el-input v-model="form.viewCount" placeholder="系统自动统计" :disabled="true" />
            </el-form-item>
          </el-col>
          <el-col :xs="24" :sm="12" :md="8" :lg="6" :xl="6">
            <el-form-item label="评论数" prop="commentCount">
              <el-input v-model="form.commentCount" placeholder="系统自动统计" :disabled="true" />
            </el-form-item>
          </el-col>
          <!-- <el-col :xs="24" :sm="12" :md="8" :lg="6" :xl="6">
            <el-form-item label="审核状态" prop="verifyStatus">
              <el-radio-group v-model="form.verifyStatus">
                <el-radio
                  v-for="dict in dict.type.ec_audit_status"
                  :key="dict.value"
                  :label="dict.value"
                >{{dict.label}}</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col> -->
          <el-col :xs="24" :sm="12" :md="8" :lg="6" :xl="6">
            <el-form-item label="上架状态" prop="publishStatus">
              <el-radio-group v-model="form.publishStatus">
                <el-radio
                  v-for="dict in dict.type.ec_currect_and_no"
                  :key="dict.value"
                  :label="dict.value"
                >{{dict.label}}</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20">
          <el-col :span="24">
            <el-form-item label="主图片" prop="mainImage">
              <image-upload v-model="form.mainImage"/>
            </el-form-item>
          </el-col>
        </el-row>


        <el-row :gutter="20">
          <el-col :span="24">
            <el-form-item label="关键词" prop="keywords">
              <el-input v-model="form.keywords" type="textarea" :rows="2" placeholder="请输入关键词" />
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20">
          <el-col :span="24">
            <el-form-item label="商品描述" prop="description">
              <editor v-model="form.description" :min-height="192"/>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20">
          <el-col :xs="24" :sm="12" :md="8" :lg="6" :xl="6">
            <el-form-item label="是否新品" prop="isNew">
              <el-radio-group v-model="form.isNew">
                <el-radio
                  v-for="dict in dict.type.ec_currect_and_no"
                  :key="dict.value"
                  :label="dict.value"
                >{{dict.label}}</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
          <el-col :xs="24" :sm="12" :md="8" :lg="6" :xl="6">
            <el-form-item label="是否热销" prop="isHot">
              <el-radio-group v-model="form.isHot">
                <el-radio
                  v-for="dict in dict.type.ec_currect_and_no"
                  :key="dict.value"
                  :label="dict.value"
                >{{dict.label}}</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
          <el-col :xs="24" :sm="12" :md="8" :lg="6" :xl="6">
            <el-form-item label="是否推荐" prop="isRecommend">
              <el-radio-group v-model="form.isRecommend">
                <el-radio
                  v-for="dict in dict.type.ec_currect_and_no"
                  :key="dict.value"
                  :label="dict.value"
                >{{dict.label}}</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
        </el-row>

        <el-form-item style="text-align: center; margin-top: 30px;">
          <el-button type="primary" @click="submitForm" :loading="loading">{{ isEdit ? '修改' : '新增' }}</el-button>
          <el-button @click="cancel">取消</el-button>
        </el-form-item>
      </el-form>
    </el-card>
  </div>
</template>

<script>
import { getProduct, addProduct, updateProduct } from "@/api/fun/product"
import { listCategory, getCategory } from "@/api/fun/category"
import { listBrand, getBrand } from "@/api/fun/brand"
import Editor from '@/components/Editor'
import IdSelector from "@/components/IdSelector"
import CodingInput from '@/components/CodingInput'
import ImageUpload from '@/components/ImageUpload'

export default {
  name: "ProductForm",
  components: {
    Editor,
    IdSelector,
    CodingInput,
    ImageUpload
  },
  dicts: ['sys_common_status', 'ec_currect_and_no', 'ec_audit_status'],
  data() {
    return {
      // 提交状态
      loading: false,
      // 是否为编辑模式
      isEdit: false,
      // 表单参数
      form: {
        productId: null,
        productCode: null,
        productName: null,
        categoryId: null,
        brandId: null,
        price: null,
        originalPrice: null,
        costPrice: null,
        stock: null,
        lowStock: 0,
        weight: null,
        volume: null,
        unit: null,
        keywords: null,
        description: null,
        mainImage: null,

        saleCount: 0,
        viewCount: 0,
        commentCount: 0,
        isNew: "0",
        isHot: "0",
        isRecommend: "0",
        status: "0",
        publishStatus: "0",
        verifyStatus: "0"
      },
      // 表单校验
      rules: {
        productCode: [
          { required: true, message: "商品编码不能为空", trigger: "blur" }
        ],
        productName: [
          { required: true, message: "商品名称不能为空", trigger: "blur" }
        ],
        price: [
          { required: true, message: "商品价格不能为空", trigger: "blur" }
        ],
        stock: [
          { required: true, message: "库存数量不能为空", trigger: "blur" }
        ]
      }
    }
  },
  created() {
    const pageType = this.$route.query.pageType
    const productId = this.$route.query.productId
    if (pageType === 'edit' && productId) {
      this.isEdit = true
      this.getProductInfo(productId)
    }
  },
  methods: {
    /** 获取商品详细信息 */
    getProductInfo(productId) {
      getProduct(productId).then(response => {
        this.form = response.data
      })
    },
    /** 表单重置 */
    reset() {
      this.form = {
        productId: null,
        productCode: null,
        productName: null,
        categoryId: null,
        brandId: null,
        price: null,
        originalPrice: null,
        costPrice: null,
        stock: null,
        lowStock: 0,
        weight: null,
        volume: null,
        unit: null,
        keywords: null,
        description: null,
        mainImage: null,

        saleCount: 0,
        viewCount: 0,
        commentCount: 0,
        isNew: "0",
        isHot: "0",
        isRecommend: "0",
        status: "0"
      }
      this.resetForm("form")
    },
    /** 取消按钮 */
    cancel() {
      this.$tab.closePage()
    },

    /** 提交按钮 */
    async submitForm() {
      this.$refs["form"].validate(async valid => {
        if (valid) {
          this.loading = true
          try {
            // 设置隐藏字段的默认值
            this.form.price = this.form.price || 0
            this.form.originalPrice = this.form.originalPrice || 0
            this.form.costPrice = this.form.costPrice || 0
            this.form.stock = this.form.stock || 0

            // 如果是新增模式，需要先确认编码
             if (this.form.productId == null) {
               console.log('=== 开始确认商品编码 ===')
               if (this.$refs.productCodeInput && this.$refs.productCodeInput.confirmCurrentCode) {
                 const confirmedCode = await this.$refs.productCodeInput.confirmCurrentCode()
                 if (!confirmedCode) {
                   this.$modal.msgError('编码确认失败，无法保存')
                   return
                 }
                 this.form.productCode = confirmedCode
                 console.log('编码确认成功:', confirmedCode)
               }
             }

            if (this.form.productId != null) {
              updateProduct(this.form).then(response => {
              this.$modal.msgSuccess("修改成功")
              // 通知父页面刷新列表
              this.$eventBus.$emit('refreshProductList')
              this.$tab.closePage()
            }).finally(() => {
              this.loading = false
            })
            } else {
              addProduct(this.form).then(response => {
              this.$modal.msgSuccess("新增成功")
              // 通知父页面刷新列表
              this.$eventBus.$emit('refreshProductList')
              this.$tab.closePage()
            }).finally(() => {
              this.loading = false
            })
            }
          } catch (error) {
            console.error('保存失败:', error)
            this.$modal.msgError('保存失败: ' + (error.message || '未知错误'))
            this.loading = false
          }
        }
      })
    },
    /** 编码生成回调 */
    handleCodeGenerated(code) {
      console.log('生成的商品编码:', code)
      // 可以在这里处理编码生成后的逻辑
    },
    // API方法
    listCategory,
    getCategory,
    listBrand,
    getBrand
  }
}
</script>

<style scoped>
.clearfix:before,
.clearfix:after {
  display: table;
  content: "";
}
.clearfix:after {
  clear: both
}
</style>
